package cn.bugDance.domain.security.servive.shiro.realm;


import cn.bugDance.domain.security.model.valobj.JwtToken;
import cn.bugDance.domain.security.servive.shiro.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


@Slf4j
@Component("jwtRealm")
public class JwtRealm extends AuthorizingRealm {

    private static JwtUtil jwtUtil = new JwtUtil();

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String jwtToken = (String) authenticationToken.getPrincipal();
        if(null == jwtToken){
            throw new NullPointerException("jwtToken为空!");
        }
        if(!jwtUtil.isVerify(jwtToken)){
            throw new UnknownAccountException("jwtToken不合法!");
        }
        String userId = (String) jwtUtil.decode(jwtToken).get("username");
        log.info("【JwtRealm->】: 用户: {}, 登录", userId);
        return new SimpleAuthenticationInfo(jwtToken, jwtToken, this.getName());
    }


    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof JwtToken;
    }


}
